package com.matrix.draft.sockettest.day11;

import io.netty.buffer.ByteBuf;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

@Slf4j
public class TestLengthField {

    // 测试LengthFieldBasedFrameDecoder
    public static void t1() {
        EmbeddedChannel channel = new EmbeddedChannel(
                // In
                new LengthFieldBasedFrameDecoder(
                        1024, 0, 8, 1, 9),
                // Duplex
                new LoggingHandler()
        );
        // 触发入站读事件
        ByteBuf buf = channel.alloc().buffer();
        MyBufferFiller filler = (b, content) -> {
            // 设计如下
            // 长度 版本号 内容
            // LEN HRD CONTENT
            // 8   1   未知
            byte[] bytes = content.getBytes(StandardCharsets.UTF_8);
            b.writeLong(bytes.length);
            b.writeByte(1);
            b.writeBytes(bytes);
        };
        filler.fill(buf, "HelloWorld");
        filler.fill(buf, "I am Netty");
        filler.fill(buf, "Java");
        channel.writeInbound(buf);
        channel.finishAndReleaseAll();
    }

    public static void main(String[] args) {
        t1();
    }

    // 自定义Consumer
    @FunctionalInterface
    public interface MyBufferFiller<A, B> {
        void fill(ByteBuf buf, String content);
    }
}
